<template>
  <div class="app-container">
    <!-- 新增门禁信息 -->
    <div>
      <p><b class="p">门禁基础信息</b></p>
      <el-form :inline="true" :model="inputModel" :rules="rules" ref="inputModel" label-width="100px"
        class="interval-top">
        <el-form-item label="门禁名称:" prop="name">
          <el-input class="input-width" style="width: 202px" v-model="inputModel.name"
            @change="isExistence(inputModel.name)"></el-input>
        </el-form-item>
        <el-form-item label="门禁编码:" prop="bianm">
          <el-input class="input-width" v-model="inputModel.bianma"></el-input>
        </el-form-item>
        <el-form-item label="方向:" prop="fangx">
          <el-select v-model="inputModel.direction" placeholder="请选择">
            <el-option v-for="item in directionList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="拓展权限:">
          <el-select v-model="inputModel.purview" placeholder="请选择">
            <el-option v-for="item in purviewList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="启用状态:" prop="delivery">
          <el-switch v-model="inputModel.delivery"></el-switch>
        </el-form-item>
      </el-form>
      <div class="">
        <b class="p">外接设备信息</b>
        <div class="move-right">
          <el-button type="primary" @click="addDevice" size="mini" v-show="isInspect">添加设备</el-button>
          <!-- <el-button @click="clearDevuce" size="mini">清空设备</el-button> -->
        </div>
      </div>
      <div v-for="item in list " :key="item.id">
        <el-form :inline="true" :model="item" :rules="rules1" ref="searchModel1" label-width="100px" class="interval-top">
          <el-form-item label="设备类型:" prop="shebType">
            <el-select v-model="item.shebType" placeholder="请选择">
              <el-option v-for="i in equipmentTypeList" :key="i.value" :label="i.label" :value="i.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备名称:" prop="shebName">
            <el-input v-model="item.shebName" placeholder="选择设备后回填" suffix-icon="el-icon-search"
              @focus="dialogStartUp(item)"></el-input>
          </el-form-item>
          <el-form-item label="设备ID:" prop="shebId">
            <el-input class="input-width" v-model="item.shebId" placeholder="选择设备后回填"></el-input>
          </el-form-item>
          <el-form-item label="方向:" prop="fangx">
            <el-select v-model="item.fangx" placeholder="请选择">
              <el-option v-for="i in directionList1" :key="i.value" :label="i.label" :value="i.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-button type="danger" icon="el-icon-delete" @click="deleteDevice(item.id)" v-show="isInspect"></el-button>
        </el-form>
      </div>
      <div style="margin-left:5rem;margin-top: .5rem;">
        <el-button type="primary" @click="submit" v-show="isInspect">提交
        </el-button>
        <el-button style="margin-left:20px" @click="back">取消</el-button>
      </div>
      <el-dialog title="选择设备" :visible.sync="dialogFormVisible" width="35%">
        <el-form :label-width="labelWidth" :model="searchModel" :inline="true">
          <el-form-item label="设备名称:" prop="name">
            <el-input class="input-width" v-model="searchModel.name"></el-input>
          </el-form-item>
          <el-button style="margin-left:2rem;" type="primary" @click="handleDownload">查询</el-button>
        </el-form>
        <!-- 设备详情表  selection 多选   index 单选 -->
        <el-table v-loading='listLoading' :data='equipmentList' element-loading-text='Loading' border fit
          highlight-current-row @row-click="selectionChangeHandle">
          <el-table-column align='center' type="index" width="55">
          </el-table-column>
          <el-table-column align='center' label='设备名称' width='190'>
            <template slot-scope='scope'>
              {{ scope.row.deviceName }}
            </template>
          </el-table-column>
          <el-table-column label='IP' width='130' align='center'>
            <template slot-scope='scope'>
              <span>{{ scope.row.networkSetting.host }}</span>
            </template>
          </el-table-column>
          <el-table-column label='账号' width='130' align='center'>
            <template slot-scope='scope'>
              <span>{{ scope.row.networkSetting.account }}</span>
            </template>
          </el-table-column>
          <el-table-column label='密码' width='120' align='center'>
            <template slot-scope='scope'>
              {{ scope.row.networkSetting.password }}
            </template>
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="currentPage" :page-size="pageSize" layout=" prev, pager, next, jumper" :total="total">
          </el-pagination>
          <el-button style="margin-top:1rem;" @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogDetermine">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { insertApiAccess, getIotDevice, getIotIdDevice, updataApiAccess, getApiAccessPageList } from "@/api/Access"
import { getApiExtendServiceList } from "@/api/ExtendServices"

export default {
  data() {
    return {
      inputModel: {
        name: '',
        bianma: '',
        delivery: true,
        direction: '',
        purview: '',
      },
      inputShebId: 0,
      list: [{
        id: 0,
        shebType: '',
        shebName: '',
        shebId: '',
        fangx: '',
        lotEquipmentId: '',
      }, {
        id: 1,
        shebType: '',
        shebName: '',
        shebId: '',
        fangx: '',
        lotEquipmentId: '',
      }],
      rules: {
        name: [{ required: true, message: '请输入门禁名称', trigger: 'blur' },
        { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }],
        fangx: [{ required: true, message: '请选择方向', trigger: 'blur' }]
      },
      rules1: {
        shebType: [{ required: true, message: '请选择设备类型', trigger: 'blur' }],
        shebName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
        shebId: [{ required: true, message: '请输入设备Id', trigger: 'blur' }],
        fangx: [{ required: true, message: '请选择方向', trigger: 'blur' }]
      },
      directionList: [{ value: 0, label: '请选择' }, { value: 1, label: '进场' }, { value: 2, label: '出场' }, { value: 3, label: '双向' }],
      directionList1: [{ value: 0, label: '请选择' }, { value: 1, label: '进场' }, { value: 2, label: '出场' }],
      purviewList: [],
      equipmentTypeList: [{ value: 0, label: '请选择' }, { value: 1, label: '摄像头' }, { value: 2, label: 'LED屏' }],
      equipmentList: [],
      listLoading: false,
      labelWidth: "80px",
      labelHeight: "32px",
      addCount: 2,
      dialogFormVisible: false,
      searchModel: { name: "" },
      dataListSelections: [],
      count: 0,
      currentPage: 1,
      total: 0,
      pageSize: 5,
      isEdit: false,
      isInspect: true,
      isExistenceFalg: false,
    }
  },
  created() {
    this.isEditJudge();
    this.getApiExtendServiceList();
  },
  methods: {
    isExistence(inputName) {
      let data = {
        skipCount: ((this.currentPage <= 1 ? 1 : this.currentPage) - 1) * this.pageSize,
        MaxResultCount: this.pageSize,
      };
      data.Name = inputName;
      getApiAccessPageList(data).then(res => {
        if (res.totalCount > 0) {
          this.isExistenceFalg = true;
          return this.$message.error('该门禁名称已存在。请修改')
        } else {
          this.isExistenceFalg = false;
        }
      });
    },
    insertJudge(equipments) {
      const flag = equipments.every(
        item => String(item.type) != "" && String(item.type) != "0"
          && String(item.lotEquipmentId) != ""
          && String(item.name) != ""
          && String(item.direction) != "" && String(item.direction) != "0"
      );
      return flag;
    },
    isEditJudge() {
      this.isInspect = this.$route.query.isEditOrInsert;
      this.isEdit = this.$route.query.isEdit || false;
      if (!this.isEdit) {
        return;
      }
      this.getApiExtendServiceList();
      let tempList = this.$route.query.accessList;
      console.log(tempList)
      //基本数据
      this.inputModel.accessId = tempList.id;
      this.inputModel.name = tempList.name;
      this.inputModel.bianma = tempList.accessNo;
      this.inputModel.direction = tempList.direction;
      this.inputModel.delivery = tempList.state == 1 ? true : false;
      if (tempList.extends.length > 0) {
        this.inputModel.purview = tempList.extends[0].extendServiceId;
      } else {
        this.inputModel.purview = "-1"
      }
      //外接设备信息
      let tempData = [];
      let tempDevice = [];
      tempList.equipments.forEach(item => {
        getIotIdDevice(item.lotEquipmentId).then(res => {
          tempDevice = res;
          tempData.push({
            id: item.id,
            shebType: item.type,
            lotEquipmentId: item.lotEquipmentId,
            shebName: tempDevice.deviceName,
            shebId: tempDevice.networkSetting.host,
            fangx: item.direction
          });
        });
      });
      this.list = tempData;
    },
    getApiExtendServiceList() {
      let data = {
        state: 1,
      };
      getApiExtendServiceList(data).then(res => {
        this.purviewList = res;
        this.purviewList.unshift({
          id: '-1',
          name: "请选择"
        })
        console.log(this.purviewList);
      })
    },
    getIotDevice(num) {
      let data =
      {
        ProductCategory: num,
        ProtocolTa: "HCNetSDK"
      }
      getIotDevice(data).then(res => {
        console.log(res);
        this.equipmentList = res;
      });
    },
    submit() {
      let directionFlag = false;
      let equipments = [];
      let data = {
        name: this.inputModel.name,
        accessNo: this.inputModel.bianma,
        direction: Number(this.inputModel.direction),
        state: this.inputModel.delivery ? 1 : 0,
      };
      if (this.inputModel.purview != "-1" && this.inputModel.purview != "") {
        data.extends = [{
          extendServiceId: this.inputModel.purview,
        }];
      }
      this.list.forEach(item => {
        equipments.push({
          type: Number(item.shebType),
          lotEquipmentId: item.lotEquipmentId,
          name: item.shebName,
          direction: Number(item.fangx)
        });
        if (this.inputModel.direction != 3) {
          if (Number(item.fangx) != Number(this.inputModel.direction)) {
            directionFlag = true;
          }
        }
      });
      data.equipments = equipments;
      //#region  必填项为空判断
      if (this.inputModel.name.length == 0) {
        return this.$message.error('请填写门禁名称')
      }
      if (this.isExistenceFalg) {
        return this.$message.error('该门禁名称已存在。请修改')
      }
      if (this.inputModel.direction == 0 || this.inputModel.direction == "") {
        return this.$message.error('请选择方向')
      }
      if (!this.insertJudge(equipments)) {
        return this.$message.error('外接设备信息为必填项')
      }
      if (directionFlag) {
        return this.$message.error('外接设备信息中的方向需与门禁基础信息中方向一致！')
      }
      //#endregion

      if (this.isEdit) {
        data.accessId = this.inputModel.accessId;
        updataApiAccess(data).then(res => {
          this.$router.push(
            {
              path: 'accessControl',
            });
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
        });
      }
      else {
        insertApiAccess(data).then(res => {
          this.$router.push(
            {
              path: 'accessControl',
            });
          this.$message({
            type: 'success',
            message: '添加成功!'
          });
        });
      }
    },
    back() {
      this.$router.push(
        {
          path: 'accessControl',
        });
    },
    getList() {
    },
    addDevice() {
      this.list.push({
        id: this.addCount,
        shebType: '',
        shebName: '',
        shebId: '',
        fangx: '',
        lotEquipmentId: '',
      })
      this.addCount++;
    },
    deleteDevice(id) {
      let list1 = [];
      this.list.forEach(item => {
        if (item.id != id) {
          list1.push(item);
        }
      });
      this.list = list1;
    },
    clearDevuce() {
      this.list = [{
        id: 0,
        shebType: '',
        shebName: '',
        shebId: '',
        fangx: '',
        lotEquipmentId: '',
      }, {
        id: 1,
        shebType: '',
        shebName: '',
        shebId: '',
        fangx: '',
        lotEquipmentId: '',
      }]
    },
    handleDownload() {
    },
    dialogStartUp(tempList) {
      if (!this.isInspect) {
        return;
      }
      this.dialogFormVisible = true;
      this.inputShebId = tempList.id;
      if (tempList.shebType == 1) {
        this.getIotDevice(5);
      } else if (tempList.shebType == 2) {
        this.getIotDevice(6);
      }
      else {
        return
      }
    },
    dialogDetermine() {
      this.list.forEach(item => {
        if (this.inputShebId === item.id) {
          item.shebName = this.dataListSelections.deviceName;
          item.shebId = this.dataListSelections.networkSetting.host;
          item.lotEquipmentId = this.dataListSelections.id;
        }
      });
      this.dialogFormVisible = false;
    },
    selectionChangeHandle(val) {
      this.dataListSelections = val
      console.log(this.dataListSelections, '123');
    },
    handleCurrentChange() {

    },
    handleSizeChange() {

    },
  }
}
</script>

<style lang="scss" scoped>
.main {
  margin: 0.2rem;
  padding: 0.2rem;
}

.search-bar {
  margin-bottom: .2rem;
  text-align: left;
  float: left;
  margin-left: .8rem;
  margin-top: .2rem;
}

.p {
  font-size: 23px;
}

.move-right {
  // width: 180px;
  // height: 30px;
  margin-bottom: 1px;
  // margin-right: 20rem;
  float: right;
}

.dialog-button {
  height: 40px;
  width: 200px;
  float: right;
}

.input-width {
  width: 202px;
}

.block {
  margin-right: .2rem;
  float: right;
}

.interval-top {
  margin-top: .16rem;
}
</style>
